package com.tennis.tennisreservation.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

import lombok.RequiredArgsConstructor;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;

@Configuration
@RequiredArgsConstructor
public class WxPayClientConfig {

    private final WxPayConfig wxPayConfig;

    /**
     * 加载商户私钥
     */
    private PrivateKey loadPrivateKey() throws Exception {
        // 处理classpath:前缀
        String path = wxPayConfig.getPay().getPrivateKeyPath();
        if (path.startsWith("classpath:")) {
            path = path.substring("classpath:".length());
            Resource resource = new ClassPathResource(path);
            try (InputStream inputStream = resource.getInputStream()) {
                return PemUtil.loadPrivateKey(inputStream);
            }
        } else {
            // 保留原来的文件系统路径支持
            java.io.FileInputStream fis = new java.io.FileInputStream(path);
            return PemUtil.loadPrivateKey(fis);
        }
    }

    /**
     * 加载微信平台证书
     */
    private X509Certificate loadWechatPayCertificate() throws Exception {
        String path = wxPayConfig.getPay().getWechatpayCertPath();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        
        if (path.startsWith("classpath:")) {
            path = path.substring("classpath:".length());
            Resource resource = new ClassPathResource(path);
            try (InputStream inputStream = resource.getInputStream()) {
                return (X509Certificate) cf.generateCertificate(inputStream);
            }
        } else {
            java.io.FileInputStream fis = new java.io.FileInputStream(path);
            return (X509Certificate) cf.generateCertificate(fis);
        }
    }

    /**
     * 初始化微信支付 HTTP 客户端
     */
    @Bean
    public CloseableHttpClient wechatPayHttpClient() {
        try {
            return WechatPayHttpClientBuilder.create()
                    .withMerchant(wxPayConfig.getPay().getMchId(),
                            wxPayConfig.getPay().getMchSerialNo(),
                            loadPrivateKey())
                    .withWechatPay(List.of(loadWechatPayCertificate()))
                    .build();
        } catch (Exception e) {
            // 出现异常时返回一个默认的HTTP客户端
            System.err.println("初始化微信支付客户端失败：" + e.getMessage());
            e.printStackTrace();
            return org.apache.http.impl.client.HttpClients.createDefault();
        }
    }
}
